#include "sysreadsqlsandsplit.h"
#include <QFile>
#include <QRegularExpression>
#include "dbquerybasethread.h"

SysReadSqlsAndSplit::SysReadSqlsAndSplit()
{

}

bool SysReadSqlsAndSplit::readFile(const QString& fileName, QString& contents)
{
    QFile file(fileName);
    if(file.open(QFile::ReadOnly))
    {
        contents = file.readAll();
        return true;
    }
    return false;
}

void SysReadSqlsAndSplit::split(const QString& contents, QStringList &l)
{
    QRegularExpression rx("[a-zA-Z][^;]*;");

    QRegularExpressionMatchIterator i = rx.globalMatch(contents);

    while (i.hasNext()) {
        QRegularExpressionMatch match = i.next();
        l << match.capturedTexts().at(0);
    }
}

void SysReadSqlsAndSplit::f_query(CnsComponentPtr com, CnsComponentPtr gnFindPathDBThread)
{
    DbQueryBaseThreadPtr p = gnFindPathDBThread.staticCast<DbQueryBaseThread>();
    QVariantHash &props = p->getProps();
    QString fileName = props["fileName"].toString();
    QString sqlString;
    bool ret=readFile(fileName, sqlString);

    if(!ret)
    {
        return;
    }
    const QSSHASH& patterns = props["patterns"].value<QSSHASH>();
    for(QSSHASH::const_iterator it = patterns.begin(); it != patterns.end(); it ++)
    {
        sqlString.replace(it.key(), it.value());
    }
    QStringList l;
    split(sqlString, l);

    props["readSqlsAndSplit"] = l;
}
